package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户登录
     */
    public Map login(String username, String password, String code, String uuid) {
        //1、比较redis中的验证和用户输入的验证码
        String redisCode = redisTemplate.opsForValue().get("CODE:" + uuid);
        //1.1 判断验证码
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //1.2 如果验证码错误，抛出异常
            throw new BusinessException("验证码错误");
        }
        //1.3 如果验证正确，删除redis验证码
        redisTemplate.delete("CODE:" + uuid);
        //2、比较用户名/密码与数据库中的是否一致
        //2.1 根据用户查询用户
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //2.2 对用户输入的密码进行加密
        password = SecureUtil.md5(password);
        //2.3 比较数据库中的密码和加密后用户输入的密码
        if(admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或者密码错误");
        }
        //3、生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //4、返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;
    }

    //获取管理员信息
    public AdminVo profile() {
        //从Threadlocal，获取管理员id
        Long id = AdminHolder.getUserId();
        //调用mapper根据id查询管理员
        Admin admin = adminMapper.selectById(id);
        //返回
        return AdminVo.init(admin);
    }
}
